package com.briup.estore.service.impl;

import com.briup.estore.common.dto.ShopCarUpdateDto;
import com.briup.estore.common.pojo.Book;
import com.briup.estore.common.pojo.ShopCar;
import com.briup.estore.common.utils.BeanCopyUtils;
import com.briup.estore.common.vo.ShopCarVO;
import com.briup.estore.dao.BookDao;
import com.briup.estore.dao.ShopCarDao;
import com.briup.estore.dao.impl.BookDaoImpl;
import com.briup.estore.dao.impl.ShopCarDaoImpl;
import com.briup.estore.service.ShopCarService;

import java.util.List;

/**
 * @Author briup-adam
 * @Date 2023/8/3 下午2:22
 * @Description
 **/

public class ShopCarServiceImpl implements ShopCarService {
    private ShopCarDao shopCarDao = new ShopCarDaoImpl();
    private BookDao bookDao = new BookDaoImpl();

    @Override
    public List<ShopCarVO> findLists(Integer userId) {
        List<ShopCar> list = shopCarDao.findByUserId(userId);
        List<ShopCarVO> shopCarVOS = BeanCopyUtils.copyList(list, ShopCarVO.class);
        shopCarVOS.forEach(i -> {
            Book book = bookDao.selectById(i.getBookId());
            i.setCover(book.getCover());
            i.setName(book.getName());
            i.setPrice(book.getPrice());
        });
        return shopCarVOS;
    }

    @Override
    public void add(int userId, Integer bookId) {
        ShopCar shopCar = shopCarDao.findByUserIdAndBookId(userId, bookId);
        if (shopCar!=null){
            shopCarDao.updateNumById(shopCar.getNum()+1,shopCar.getId());
        }else {
            shopCarDao.save(userId, bookId);
        }


    }

    @Override
    public void updateNum(ShopCarUpdateDto dto) {
        shopCarDao.updateNumById(dto.getNum(), dto.getId());
    }

    @Override
    public void deleteByIds(int... ids) {
        for (int id : ids) {
            shopCarDao.deleteById(id);
        }
    }
}
